<template>
  <a-table
    rowKey="id"
    size="middle"
    bordered
    :loading="loading"
    :columns="columns"
    :dataSource="tableDataWithTotal"
    :pagination="false"
  >
    <template slot="htmlSlot" slot-scope="text">
      <div v-html="text"></div>
    </template>

    <template slot="imgSlot" slot-scope="text,record">
      <div style="font-size: 12px;font-style: italic;">
        <span v-if="!text">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;"/>
      </div>
    </template>

    <template slot="fileSlot" slot-scope="text">
      <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
      <a-button
        v-else
        ghost
        type="primary"
        icon="download"
        size="small"
        @click="downloadFile(text)"
      >
        <span>下载</span>
      </a-button>
    </template>
  </a-table>
</template>

<script>
import { getAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'CwZyryzfgjjSubTable',
  mixins: [JeecgListMixin],
  props: {
    record: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      description: '在职人员住房公积金测算明细表内嵌列表',
      disableMixinCreated: true,
      loading: false,
      dataSource: [],
      // 所有需要计算合计的字段（dataIndex集合，共17个）
      totalFields: [
        'postWage', 'incrementalStep', 'livingAllowance', 'workAllowance', 'sanitationFee',
        'hmbt', 'jkbybt', 'healthSubsidies', 'housingSubsidy', 'jcjxj',
        'ndkhj', 'apj', 'wxjbt', 'zzyf', 'gjjjfjs',
        'yjce', 'njce',
        'yyfhj', 'ssx'
      ],
      columns: [
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '财政/非财政',
          align: 'center',
          dataIndex: 'czFcz'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '年度',
          align: 'center',
          dataIndex: 'year_dictText'
        },
        {
          title: '职称 (职务)',
          align: 'center',
          dataIndex: 'duty',
        },
        {
          title: '岗位工资',
          align: 'center',
          dataIndex: 'postWage',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '薪级工资',
          align: 'center',
          dataIndex: 'incrementalStep',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '生活性补贴',
          align: 'center',
          dataIndex: 'livingAllowance',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '工作性津贴',
          align: 'center',
          dataIndex: 'workAllowance',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '卫生费',
          align: 'center',
          dataIndex: 'sanitationFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '回民补贴',
          align: 'center',
          dataIndex: 'hmbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '艰苦边远补贴',
          align: 'center',
          dataIndex: 'jkbybt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '保健费（测试中心',
          align: 'center',
          dataIndex: 'healthSubsidies',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '13%房补',
          align: 'center',
          dataIndex: 'housingSubsidy',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '基础绩效奖',
          align: 'center',
          dataIndex: 'jcjxj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '月应发合计',
          align: 'center',
          dataIndex: 'yyfhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '发放的十三薪',
          align: 'center',
          dataIndex: 'ssx',
          customRender: (text) => this.formatNumber(text)
        },

        {
          title: '发放的年度考核奖',
          align: 'center',
          dataIndex: 'ndkhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '发放的安全奖',
          align: 'center',
          dataIndex: 'apj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '发放的未休假补贴',
          align: 'center',
          dataIndex: 'wxjbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '在职月份',
          align: 'center',
          dataIndex: 'zzyf',
          customRender: (text) => this.formatNumber(text, 0) // 月份保留整数
        },
        {
          title: '公积金缴费基数（年）',
          align: 'center',
          dataIndex: 'gjjjfjs',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '月缴存额',
          align: 'center',
          dataIndex: 'yjce',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '年缴存额',
          align: 'center',
          dataIndex: 'njce',
          customRender: (text) => this.formatNumber(text)
        },
      ],
      url: {
        listByMainId: '/cw/cwZyryzfgjjTj/queryCwZyryzfgjjByMainId',
      },
    }
  },
  computed: {
    // 带合计行的完整数据
    tableDataWithTotal() {
      if (!this.dataSource || this.dataSource.length === 0) return []

      // 深拷贝原始数据，避免污染原数据
      const newData = JSON.parse(JSON.stringify(this.dataSource))
      // 计算所有字段合计
      const fieldTotals = this.calcAllFieldTotals()

      // 构建合计行
      const totalRow = {
        id: 'total_' + new Date().getTime(), // 唯一ID，避免rowKey重复警告
        name: '合计',
        czFcz: '',
        unit_dictText: '',
        year_dictText: '',
        duty: '',
        // 填充所有合计字段值
        postWage: fieldTotals.postWage,
        incrementalStep: fieldTotals.incrementalStep,
        livingAllowance: fieldTotals.livingAllowance,
        workAllowance: fieldTotals.workAllowance,
        sanitationFee: fieldTotals.sanitationFee,
        hmbt: fieldTotals.hmbt,
        jkbybt: fieldTotals.jkbybt,
        healthSubsidies: fieldTotals.healthSubsidies,
        housingSubsidy: fieldTotals.housingSubsidy,
        jcjxj: fieldTotals.jcjxj,
        ndkhj: fieldTotals.ndkhj,
        apj: fieldTotals.apj,
        wxjbt: fieldTotals.wxjbt,
        zzyf: fieldTotals.zzyf,
        gjjjfjs: fieldTotals.gjjjfjs,
        yjce: fieldTotals.yjce,
        yyfhj: fieldTotals.yyfhj,
        ssx: fieldTotals.ssx,
        njce: fieldTotals.njce

      }

      newData.push(totalRow)
      return newData
    }
  },
  watch: {
    record: {
      immediate: true,
      handler() {
        if (this.record) {
          this.loadData(this.record)
        }
      }
    }
  },
  methods: {
    loadData(record) {
      this.loading = true
      this.dataSource = []
      getAction(this.url.listByMainId, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [] // 兼容无数据场景
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 数字格式化通用方法
     * @param text 原始值
     * @param decimal 小数位数（默认2位，在职月份用0位）
     */
    formatNumber(text, decimal = 2) {
      const num = Number(text)
      // 处理非数字/空值，返回规范的0值格式
      return isNaN(num) ? `0${decimal > 0 ? '.' + '0'.repeat(decimal) : ''}` : num.toFixed(decimal)
    },

    /**
     * 批量计算所有目标字段的合计
     */
    calcAllFieldTotals() {
      // 初始化所有合计字段为0
      const totals = this.totalFields.reduce((obj, field) => {
        obj[field] = 0
        return obj
      }, {})

      // 遍历数据累加每个字段值（兼容空值和非数字）
      this.dataSource.forEach(item => {
        this.totalFields.forEach(field => {
          const val = Number(item[field])
          totals[field] += isNaN(val) ? 0 : val
        })
      })

      // 格式化所有合计结果（在职月份保留0位小数，其他保留2位）
      this.totalFields.forEach(field => {
        const decimal = field === 'zzyf' ? 0 : 2
        totals[field] = totals[field].toFixed(decimal)
      })

      return totals
    },

    // 空实现方法，避免报错（保持Jeecg模板结构一致性）
    downloadFile(text) {},
    getImgView(text) {
      return text
    }
  },
}
</script>

<style scoped>
/* 合计行样式优化，突出显示且适配多列表格 */
::v-deep .ant-table-tbody tr:last-child {
  background-color: #fdf2f8 !important;
}
::v-deep .ant-table-tbody tr:last-child td {
  font-weight: 600 !important;
  border-top: 2px solid #e53e3e !important;
  color: #c53030 !important;
  text-align: center !important;
  white-space: nowrap !important;
}

/* 表格横向滚动和列宽优化，适配22列表格 */
::v-deep .ant-table-wrapper {
  overflow-x: auto !important;
  min-width: 1400px !important;
}
::v-deep .ant-table-column-title {
  white-space: nowrap !important;
  font-size: 11px !important;
  padding: 8px 4px !important;
}
/* 数据单元格样式优化，提升可读性 */
::v-deep .ant-table-tbody td {
  white-space: nowrap !important;
  font-size: 11px !important;
  padding: 8px 4px !important;
}
/* 表头样式优化，避免挤压 */
::v-deep .ant-table-thead th {
  white-space: nowrap !important;
}
</style>